<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { dateFormatStr } from '../../../common/utils/normalUtils'

const emit = defineEmits(['update:modelValue', 'update:start', 'update:end', 'change'])
  const props = defineProps({
    modelValue: {
      type: Array
    },
    start: {
      type: String
    },
    end: {
      type: String
    },
    format: {
      type: String,
      default: 'yyyy-MM-dd' // yyyy-MM-dd HH:mm:ss
    },
    changeData: {
      type: Boolean,
      default: false
    },
    stringValue: {
      type: Boolean,
      default: true
    }
  })
const state:any = reactive({
  dateValue: [],
  startValue: '',
  endValue: ''
})

/**
 * 初始化日期
 * @param val
 */
const initValue = (start:any, end:any) => {
  if (start && end) state.dateValue = [new Date(start), new Date(end)]
}

/**
 * 变化处理
 */
const changeHandler = () => {
  if (state.dateValue && state.dateValue.length === 2) {
    state.startValue = dateFormatStr(state.dateValue[0], props.format)
    state.endValue = dateFormatStr(state.dateValue[1], props.format)
  }
  emit('update:start', state.startValue)
  emit('update:end', state.endValue)
  emit('update:modelValue', [state.startValue, state.endValue])
  emit('change', props.changeData ? state.dateValue : state.value)
}

watch(() => props.start, (val:any) => {
  initValue(val, props.end)
})
watch(() => props.end, (val:any) => {
  initValue(props.start, val)
})
watch(() => props.modelValue, (val:any) => {
  initValue(val ? val[0] : '', val ? val[1] : '')
})

onMounted(() => {
  initValue(props.start, props.end)
})

</script>

<template>
  <el-date-picker v-model="state.dateValue"
                  type="datetimerange"
                  @change="changeHandler" />
</template>

<style scoped lang="scss">

</style>
